package com.hj.common.exception;

import com.hj.common.pojo.model.AjaxResult;
import com.hj.common.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.RedisConnectionFailureException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 全局异常处理器
 *
 * @author Administrator
 * @version 1.0
 **/
@ControllerAdvice//与@Exceptionhandler配合使用实现全局异常处理
public class GlobalExceptionHandler {
    private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    //捕获Exception异常
    @ExceptionHandler(value = RuntimeException.class)
    @ResponseBody
    //@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public AjaxResult processExcetion(RuntimeException e) {
        //解析异常信息
        //如果是系统自定义异常，直接取出errCode和errMessage
        if (e instanceof BusinessException) {
            LOGGER.info(e.getMessage(), e);
            //解析自定义异常信息
            BusinessException businessException = (BusinessException) e;
            if (StringUtils.isNull(businessException.getCode())) {
                return AjaxResult.error(e.getMessage());
            }
            return AjaxResult.error(businessException.getCode(),businessException.getMessage());
        }

        if (e.getCause() instanceof BusinessException){
            LOGGER.info(e.getCause().getMessage());
            return AjaxResult.error(e.getCause().getMessage());
        }

        if (e instanceof RedisConnectionFailureException){
            LOGGER.error("redis连接异常：", e);
            return AjaxResult.error("redis连接异常");
        }

        LOGGER.error("系统异常：", e);
        //统一定义为系统未知错误
        return AjaxResult.error("当前服务器正忙 请稍后重试");

    }

}
